package com.rimi.lzhg.service.impl;

import com.rimi.lzhg.dao.MenuMapper;
import com.rimi.lzhg.entry.Menu;
import com.rimi.lzhg.entry.MenuExample;
import com.rimi.lzhg.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuMapper menuMapper;


    @Override
    public Menu getMenuByName(String menuName) {
        if (StringUtils.isEmpty(menuName)){
            return null;
        }
        MenuExample example=new MenuExample();
        example.createCriteria().andNameEqualTo(menuName);
        List<Menu> menus = menuMapper.selectByExample(example);
        if(menus.size()>0){
            return menus.get(0);
        }
        return null;
    }

    @Override
    public List<Menu> getUserList(Menu menu) {
        MenuExample menuExample=new MenuExample();
        MenuExample.Criteria criteria = menuExample.createCriteria().andIsDisableEqualTo(0);
        if (menu!=null){
            //添加模糊查询条件
            if(menu.getName()!=null&&!"".equals(menu.getName())){
                criteria.andNameLike("%"+menu.getName()+"%");
            }
            if(menu.getTypeId()!=null){
                criteria.andTypeIdEqualTo(menu.getTypeId());
            }
        }
        return menuMapper.selectByExample(menuExample);
    }

    @Override
    public Menu getUserById(Integer id) {
        return menuMapper.selectByPrimaryKey(id);
    }

    @Override
    public boolean saveMenu(Menu menu) {
        if(menu==null){
            return false;
        }
        if(menu.getImgUrl()==null){
            menu.setImgUrl("default.jpg");
        }
        menu.setUpTime(new Date());
        menu.setIsDisable(0);
        if(menuMapper.insert(menu)>0){
            return true;
        }
        return false;
    }

    @Override
    public boolean updateMenu(Menu menu) {
        if(menuMapper.updateByPrimaryKeySelective(menu)>0){
            return true;
        }
        return false;
    }

    @Override
    public boolean deleteMenuById(Integer id) {
        Menu menu = new Menu();
        menu.setIsDisable(1);
        menu.setId(id);
        //状态删除
        if(menuMapper.updateByPrimaryKeySelective(menu)>0){
            return true;
        }
        return false;
    }

    @Override
    public List<Menu> getUserListByIds(String menuIds) {
        //截取获取到所有的菜单ID数组
        String[] ids = menuIds.split(",");
        List strings = Arrays.asList(ids);
        //构建查询条件
        MenuExample menuExample = new MenuExample();
        MenuExample.Criteria criteria = menuExample.createCriteria().andIdIn(strings);
        return menuMapper.selectByExample(menuExample);
    }
}
